<?php
/**
* A dashboard widget that displays a list of recent activity.
*
* Copyright (c) 2009 James Gauld <james@jamesgauld.net>
* This file is part of Scribble.
* @license http://www.scribblecms.co.uk/license.txt
*
* @package Scribble
*/
use Buan\Model;
use Buan\ModelCriteria;
use Buan\ModelManager;
use Buan\UrlCommand;
class DWidgetRecentActivity implements IScribbleDashboardWidget {

	public function getBody() {

		// Prep view
		$v = new ScribbleAdminView();
		$v->setSource(dirname(__FILE__).'/recent-activity-body.tpl.php');

		// Load recent messages.
		// Format the message strings, replacing identifiers with relevant links.
		// This will eventually be restricted so only certain users can view other
		// users' activity
		$c = new ModelCriteria();
		$c->setRange(0, 5);
		$c->addOrder('datecreated', 'DESC');
		$messages = ModelManager::select('Log', $c);
		foreach($messages as $m) {

			// Pre-escape message so we can add HTML markup and echo it directly to
			// output
			$m->message = htmlentities($m->message, ENT_COMPAT, 'UTF-8');

			// References to Pages
			if(preg_match("/page:(.*?):([^\s]+)/", $m->message, $p)) {
				$page = Model::create('Page');
				$page->id = $p[1];
				if($page->getModelManager()->load($page)) {
					$sitePrefix = $page->findRelatives('Site')->get(0)->prefix;
				}
				else {
					$sitePrefix = 'unknown-site';
				}
				$m->message = preg_replace("/page:(.*?):([^\s]+)/", '<a href="http://'.$sitePrefix.UrlCommand::createUrl('scribble', 'page').'/$1">'.$sitePrefix.'$2</a>', $m->message);
			}

			// References to Users
			$m->message = preg_replace("/user:(.*?):([^\s]+)/", '<a href="'.UrlCommand::createUrl('scribble', 'auth', 'user').'/$1">$2</a>', $m->message);

			// References to Roles
			$m->message = preg_replace("/role:(.*?):([^\s]+)/", '<a href="'.UrlCommand::createUrl('scribble', 'auth', 'role').'/$1">$2</a>', $m->message);
		}
		$v->messages = $messages;

		// Result
		return $v;
	}

	public function getTitle() {
		return 'Recent Activity';
	}
}
?>